#include "main.h"

// 要求将所有代码写在本文件内

int ListInitiate(SLNode **head)/*初始化*/ {
    *head = (SLNode*)malloc(sizeof(SLNode));
    if(!*head)return 1;
    else(*head)->next=NULL;
    return 0;
}

int ListLength(SLNode *head) /* 单链表的长度*/{
     int s=-1;
     for(s;head;s++)
     {head=head->next;
     }
    return s;
}

int ListInsert(SLNode *head, int i, DataType x) {
    int j=-1;
    SLNode *p;
        p=head;
    while (p&&j<i-1){
     p=p->next;
        ++j;}
    if(!p||j>i-1)return 0;
    SLNode *h= (SLNode*)malloc(sizeof (SLNode));
    h->data=x;
    h->next=p->next;
    p->next=h;
    return 1;
}

int ListDelete(SLNode *head, int i, DataType *x) {
    int j=-1;
    SLNode *p;
    p=head;
    while (p->next&&j<i-1)
    {p=p->next;++j;}
    if(!(p->next)||j>i-1)return 0;
    SLNode *m;
    m=p->next;
    p->next=m->next;
    *x=m->data;
    free(m);
  return 1 ;
}

int ListGet(SLNode *head, int i, DataType *x) {
    SLNode *p=head;int j=-1;
    while (head&&j<i){
        p=p->next;
        j++;
    }
    if(!head||j>i)return 0;
    *x=p->data;

  return 1;
}

int Destroy(SLNode **head)
{SLNode *p,*s;
    p = *head;
    while (p!=NULL){
        s = p;
        p = p->next;
        free(s);
    }
    if(*head =NULL)return 0;
    else
        return 1;
}

void main(void) {
    SLNode *head;
    int i , x;
    ListInitiate(&head);/*初始化*/
    for(i = 0; i < 10; i++) {
        if(ListInsert(head, i, i+1) == 0) /*插入10个数据元素*/
        {
            printf("错误! \n");
            return;
        }
    }

    if(ListDelete(head, 4, &x) == 0) { /*删除数据元素5*/
        printf("错误! \n");
        return;
    }
    printf("%d\n", ListLength(head));

    for(i = 0; i < ListLength(head); i++) {
        if(ListGet(head, i, &x) == 0) /*取元素*/
        {
            printf("错误! \n");
            return ;
        }
        else printf("%d    ", x);/*显示数据元素*/
    }

    Destroy(&head);
}
